package com.aisile.crowd_funding.system.shiro;

import com.aisile.crowd_funding.common.config.Constant;
import com.aisile.crowd_funding.common.utils.MD5Utils;
import com.aisile.crowd_funding.system.pojo.SysUser;
import com.aisile.crowd_funding.system.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @标题 MyRealm
 * @作者 Mr.chen
 * @创建日期 2018/12/5 16:19
 * @版本号 1.0
 **/
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserService userServuce;
    /**
     * 授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = MD5Utils.encrypt(new String(token.getPassword()));
        SysUser user = userServuce.findByName(username);
        if(user==null){
            throw new UnknownAccountException("账户不存在");
        }
        if(user.getPassword().equals(password)){
           throw new AuthenticationException("密码错误");
        }
        if(Constant.USER_STATUS==user.getStatus()){
            throw new LockedAccountException("账户锁定");
        }
        //根据用户名  去数据库  查用户
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        return info;
    }


    public static  void  main(String[] args){
        String str = "123456";
        System.out.println(MD5Utils.encrypt(str));
    }
}
